package com.mmall.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * Created by hanchao on 2018/1/9.
 */
@Service("userService")
public class UserServiceImpl  extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public ServerResponse login(String username, String password) {
        int resultCount =userMapper.checkUsername(username);
        if(resultCount==0)
            return  ServerResponse.createdByErrorMessage("用户名不存在");
        //TODO MD5 密码
        String MD5Password =MD5Util.MD5EncodeUtf8(password);
        User user = userMapper.selectLogin(username,MD5Password);
        if(user==null)
            return ServerResponse.createdByErrorMessage("密码错误");
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createdBySuccess("登录成功",user);
    }

    @Override
    public ServerResponse<String> register(User user) {
      ServerResponse<String> validResponse =this.checkValid(user.getUsername(),Const.USERNAME);
      if(!validResponse.isSuccess()){
            return validResponse;
      }
      validResponse =this.checkValid(user.getEmail(),Const.EMAIL);
      if(!validResponse.isSuccess()){
            return validResponse;
      }
        user.setRole(Const.Role.ROLE_CUSTOMER);
        //TODO MD5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        int resultCount =userMapper.insert(user);
        if(resultCount == 0){
            return ServerResponse.createdByErrorMessage("注册失败");
        }
        return  ServerResponse.createdBySuccessMessage("注册成功");
    }

        public ServerResponse<String> checkValid(String str,String type){
        if(StringUtils.isNotBlank(type)){
            //校验
            if(Const.USERNAME.equals(type)){
                int resultCount = userMapper.checkUsername(str);
                if(resultCount>0){
                    return ServerResponse.createdByErrorMessage("用户名已存在");
                }
            }else if(Const.EMAIL.equals(type)){
                EntityWrapper<User> ew= new EntityWrapper<User>();
                User user = new User();
                user.setEmail(str);
                ew.setEntity(user);
                int resultCount = userMapper.selectCount(ew);
                if(resultCount>0){
                    return ServerResponse.createdByErrorMessage("email已存在");
                }
            }
        }else{
            return ServerResponse.createdByErrorMessage("参数错误");
        }
        return ServerResponse.createdBySuccessMessage("检验成功");
        }

        public ServerResponse selectQuestion(String username){
            ServerResponse validResponse =checkValid(username,Const.USERNAME);
            if(validResponse.isSuccess()){
               return ServerResponse.createdByErrorMessage("用户不存在");
            }
            String question =userMapper.selectQusetionByUsername(username);
            if(StringUtils.isNotBlank(question)){
                return ServerResponse.createdBySuccess(question);
            }else{
                return ServerResponse.createdByErrorMessage("找回密码的问题是空的");
            }
        }

    public  ServerResponse<String> forgetCheckAnswer(String username,String question,String answer){
            int resultCount =userMapper.checkAnswer(username,question,answer);
            if (resultCount>0){
                //这个问题和答案是这个用户的，切实正确的
                String forgetToken = UUID.randomUUID().toString();
                TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);
                return ServerResponse.createdBySuccess();
            }
                return ServerResponse.createdByErrorMessage("问题的答案错误");

    }

    public ServerResponse<String> forgetRestPasswored(String username,String passwordNew,String forgetToken){
        if(StringUtils.isBlank(forgetToken)){
            return ServerResponse.createdByErrorMessage("参数错误，无token信息");
        }
        ServerResponse validResponse = this.checkValid(username,Const.USERNAME);
        if(validResponse.isSuccess()){
            return ServerResponse.createdByErrorMessage("用户不存在");
        }
        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);
        if(StringUtils.isBlank(token)){
            return ServerResponse.createdByErrorMessage("token无效（过期）");
        }
        if(StringUtils.equals(forgetToken,token)){
            String md5Password = MD5Util.MD5EncodeUtf8(passwordNew);
            int resultCount =userMapper.updatePasswordByUsername(username,md5Password);
            if(resultCount>0){
                return ServerResponse.createdBySuccessMessage("修改密码成功");
            }

        }else{
            return ServerResponse.createdByErrorMessage("token错误，请重新获取重置密码的token");
        }
        return ServerResponse.createdByErrorMessage("修改密码失败");
    }


    public ServerResponse<String> resetPassword(String passwordOld,String passwordNew,User user){
        //防止横向越权，要校验一下这个用户的旧密码，一定要制定是这个用户，因为我们会查询一个count(1),如果不指定id,那么这个结果一定是true;
        int resultCount =userMapper.checkPasswod(MD5Util.MD5EncodeUtf8(passwordOld),user.getId());
        if(resultCount == 0){
            return ServerResponse.createdByErrorMessage("旧密码错误");
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount > 0){
            return  ServerResponse.createdBySuccessMessage("密码修改成功");
        }
        return ServerResponse.createdByErrorMessage("密码修改失败");
    }

    public ServerResponse<User> updateInfomation(User user){
        //username 是不能更新的
        //email 也要进行教研，教研新的email是不是已经存在，并且存在的email如果相同的话，不能是当前这个用户的。
        int resutCount = userMapper.checkEmailByUserId(user.getEmail(),user.getId());
        if(resutCount>0){
            return ServerResponse.createdByErrorMessage("email已存在，请更换email再尝试更新");
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());
        int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if (updateCount>0){
            return ServerResponse.createdBySuccessMessage("更新用户信息成功");
        }
        return ServerResponse.createdByErrorMessage("更新用户信息失败");
    }
    public ServerResponse<User> getInfomation(Integer userId){
        User user = userMapper.selectByPrimaryKey(userId);
        if(user==null){
            return ServerResponse.createdByErrorMessage("找不到当前用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createdBySuccess(user);
    }

    //backend
    public ServerResponse checkAdminRole(User user){
        if(user != null && user.getRole() == Const.Role.ROLE_ADMIN){
            return ServerResponse.createdBySuccess();
        }
        return  ServerResponse.createdByError();
    }
}
